//1.引入Vue
import Vue from "vue";

//1.引入Vuex
import Vuex from "vuex";


//3.使用插件
Vue.use(Vuex)


//数据持久化
const todoVuex = localStorage.getItem("todoVuex")

//(1).创建state保存数据
const state = {
    todoList: todoVuex ? JSON.parse(todoVuex).todoList : [] , 
    isCheccked: todoVuex ? JSON.parse(todoVuex).isCheccked : false 
}

//(2).创建mutations处理同步修改数据
const mutations = {
    //1.添加
    addTodo(state , newTodo){
        state.todoList.unshift(newTodo);
        //每次修改数据后保存到本地
        localStorage.setItem("todoVuex" , JSON.stringify(state))
    },

    //2.单个切换
    asignChecked(state , payload){
        state.todoList =  state.todoList.map((item) => {
            return (
                item.id === payload ? {...item , done: !item.done} : item
              )
        })
        //每次修改数据后保存到本地
        localStorage.setItem("todoVuex" , JSON.stringify(state))
    },


    //3.单个删除
    asignDelete(state , payload){
      //删除提示
      const isDelete = confirm("确定要删除吗")
      if(!isDelete) return

      state.todoList =  state.todoList.filter((item) => {
        return  item.id !== payload
        })
        //每次修改数据后保存到本地
        localStorage.setItem("todoVuex" , JSON.stringify(state))
    },

    //4.全选
    allChecked(state , value){
        state.todoList = state.todoList.map((item) => {
            return {...item , done: value}
        })
        //每次修改数据后保存到本地
        localStorage.setItem("todoVuex" , JSON.stringify(state))
    },

    //5.清除以完成
    deleteSuccess(state){
        state.todoList = state.todoList.filter((item) => !item.done )
        //每次修改数据后保存到本地
        localStorage.setItem("todoVuex" , JSON.stringify(state))
    }
    
}


//4.创建store对象 (Vuex的实例)
export default new Vuex.Store({
    state,
    mutations,
})
